<template>
  <van-list
  v-model:loading="loading"
  :finished="finished"
  finished-text="没有更多了"
  :error="error"
  error-text="加载失败，请点击重试"
  :immediate-check="false"
  @load="onLoad"
>
<!-- 评论 -->
  <CommentItem v-for="item in list" :key="item.com_id" :comment="item"
  @deleteCommentLike="deleteCommentLike(item)"
  @addCommentLike="addCommentLike(item)"
  @reply-click="$emit('reply-click',$event)"
  ></CommentItem>
</van-list>
</template>

<script>
import { ref } from 'vue'
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  props: {
    source: {
      type: [Number, String],
      required: true
    },
    list: {
      type: Array,
      default: () => []// 默认为空数组的写法
    },
    type: {
      type: String,
      // 自定义Prop数据验证
      validator (value) {
        return ['a', 'c'].includes(value)// 传入数值必须被包含
      },
      default: 'a'
    }
  },
  components: {
    CommentItem
  },
  created () { this.onLoad() }, // 开局调用获取红点
  setup (props, context) {
    // const list = ref([])
    const loading = ref(false)
    const finished = ref(false)
    const offset = ref(null)
    const error = ref(false)
    const onLoad = async () => {
      loading.value = true // 关闭初始化时立即执行的滚动检查加载后不会自动进入loading了，因此手动开启
      // 异步更新数据
      try {
        const { data } = await getComments({
          type: props.type, // a评论，c评论的回复
          source: props.source.toString(), // 文章id或评论id
          offset: offset.value // 类似页码
        })
        const { results } = data.data

        // 把评论相关发给父组件,腾转挪移之让父组件生成列表
        context.emit('onload-success', data.data)
        // 判断后面是否还有数据
        if (results.length) {
          offset.value = data.data.last_id
        } else {
          finished.value = true
        }
      } catch (err) {
        error.value = true
      }
      loading.value = false
    }
    function deleteCommentLike (item) {
      item.is_liking = false
      item.like_count--
    }
    function addCommentLike (item) {
      item.is_liking = true
      item.like_count++
    }
    return {
      onLoad,
      loading,
      finished,
      error,
      deleteCommentLike,
      addCommentLike
    }
  }
}
</script>

<style>

</style>
